In computer science, partial sorting is a relaxed variant of the sorting problem. Total sorting is the problem of returning a list of items such that its elements all appear in order, while partial sorting is returning a list of the k smallest (or k largest) elements in order. The other elements (above the k smallest ones) may also be sorted, as in an in-place partial sort, or may be discarded, which is common in streaming partial sorts. A common practical example of partial sorting is computing the "Top 100" of some list.
In terms of indices, in a partially sorted list, for every index i from 1 to k, the i-th element is in the same place as it would be in the fully sorted list: element i of the partially sorted list contains order statistic i of the input list.
Common in current (as of 2022) C++ STL implementations is a pass of heapselect for a list of k elements, followed by a heapsort for the final result.
'''function''' partial_quicksort(A, i, j, k) '''is'''
'''if''' i < j '''then'''
p ← pivot(A, i, j)
p ← partition(A, i, j, p)
partial_quicksort(A, i, p-1, k)
'''if''' p < k-1 '''then'''
partial_quicksort(A, p+1, j, k)
The resulting algorithm is called partial quicksort and requires an expected time of only , and is quite efficient in practice, especially if a selection sort is used as a base case when becomes small relative to . However, the worst-case time complexity is still very bad, in the case of a bad pivot selection. Pivot selection along the lines of the worst-case linear time selection algorithm (see ) could be used to get better worst-case performance. Partial quicksort, quickselect (including the multiple variant), and quicksort can all be generalized into what is known as a chunksort.
Heaps lead to an "online heapselect" solution to incremental partial sorting: first build a heap, in linear time, from the complete input array to produce a min-heap. Then extract the minimum of the heap times.
A different incremental sort can be obtained by modifying quickselect. The version due to Paredes and Navarro maintains a stack of pivots across calls, so that incremental sorting can be accomplished by repeatedly requesting the smallest item of an array from the following algorithm:
Algorithm returns the 'th smallest element in
The stack is initialized to contain only the length of . -sorting the array is done by calling for ; this sequence of calls has average-case complexity , which is asymptotically equivalent to . The worst-case time is quadratic, but this can be fixed by replacing the random pivot selection by the median of medians algorithm.
|
|